<?php

namespace common\models\search;


use common\models\File;
use yii\base\Model;
use yii\data\ActiveDataProvider;

class FileSearch extends Model
{
    public $id;

    public $name;

    public $size;

    public $user;

    public $created_at;

    public function rules()
    {
        return [
            [['id', 'name', 'size', 'user', 'created_at'], 'safe'],
        ];
    }

    /**
     * @param $params
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = File::find()->from(File::tableName() . ' file')->joinWith('user');
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => ['id' => SORT_DESC],
                'attributes' => [
                    'id' => [
                        'asc' => ['id' => SORT_ASC],
                        'desc' => ['id' => SORT_DESC],
                    ],
                    'name' => [
                        'asc' => ['file_name' => SORT_ASC],
                        'desc' => ['file_name' => SORT_DESC],
                    ],
                    'file_size' => [
                        'asc' => ['file_size' => SORT_ASC],
                        'desc' => ['file_size' => SORT_DESC],
                    ],
                    'created_at' => [
                        'asc' => ['created_at' => SORT_ASC],
                        'desc' => ['created_at' => SORT_DESC],
                    ],
                    'user' => [
                        'asc' => ['user_id' => SORT_ASC],
                        'desc' => ['user_id' => SORT_DESC],
                    ]
                ]
            ]
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere(['id' => $this->id]);
        $query->andFilterWhere(['like', 'file_name', $this->name]);
        $query->andFilterWhere(['like', 'username', $this->user]);

        foreach (['created_at'] as $attribute) {
            if ($this->$attribute !== '') {
                $parts = array_map('trim', explode('/', $this->$attribute));
                if (count($parts) == 2) {
                    if ($parts[0] === $parts[1]) {
                        if ($parts[0] === date('Y-m-d')) {
                            $parts[1] .= ' ' . date('H:i:s');
                        }
                        if ($parts[0] == date('Y-m-d', strtotime('yesterday'))) {
                            $parts[1] = date('Y-m-d');
                        }
                    }

                    $query->andFilterWhere(['between', 'file.' . $attribute, strtotime($parts[0]), strtotime($parts[1])]);
                } else {
                    $query->andFilterWhere([$attribute => 'file.'. $this->$attribute]);
                }
            }
        }

        return $dataProvider;
    }
}
